#ifndef FLASHFS_H
#define FLASHFS_H
#ifdef ARDUINO

#include <Arduino.h>
#include "SPI.h"

#endif

#include "lfs.h"

#ifdef USE_SPIFLASH
#include <SPIFlash.h>
#endif
using byte = unsigned char;

class FlashFs {
public:
    FlashFs() = default;;
#ifdef USE_SPIFLASH

    int begin(SPIFlash *spi, uint32_t block_count);

#endif

    int mount();

    static int unmount();

    int format();

    int info();

    static int dir(const char *dir_name = "/", byte *filelist = nullptr, int buf_len = 0);

    static uint32_t flash_size();

    static uint32_t flash_chip_code();

    static void stat(const char *filename, lfs_info *fdd);

    static int unlink(const char *filename);

    static int rmdir(const char *dirname);

    static int closedir(lfs_dir_t *dir);

    static int opendir(lfs_dir_t *dir, const char *dirname);

    static int readdir(lfs_dir_t *dir, lfs_info *info);

    static int rename(const char *, const char *);

    static int mkdir(const char *dirname);

    static void clear();

    lfs_config cfg;
    uint32_t used_space, total;

    int dir_buf(const char *dir, char *buffer, int max_len);
};

//与LWIP定义冲突
#undef read
#undef write
#undef close

class FlashFile {
public:
    FlashFile() = default;

    int begin() { return 1; };

    int open_rdonly(const char *filename);

    int open_write(const char *filename); //写文件,文件不存在则创建,覆盖旧数据
    int read(char *buf, int len);

    int write(const char *buf, int len);

    int close();

    int opened() const;

    int eof() const;

    int fseek(int, int);

    int rewind();

    int fflush();

    const char *filename;

    static int stat(const char *filename);

    static int unlink(const char *filename);

    int exists(const char *filename) { return stat(filename); };
#ifdef ARDUINO

    int exists(String &filename) { return exists(filename.c_str()); };

    static FlashFile *open(String string, const char *string1);

#endif
    lfs_file_t fd;

    int available() {
        return !eof();
    };

    int read() {
        char c;
        read(&c, 1);
        return c;
    };

    void end() { close(); };

    int size(const char *filename) const;

    int open_append(const char *string);

    int open_rw(const char *name);
};

int flash_rename(const char *, const char *);

extern FlashFs LittleFS;
#endif
